import React from 'react';
import {Form,Input,Button,notification} from 'antd'
import service from '../../api'
import "./Login.scss"
import { useDispatch } from 'react-redux'
import { useNavigate } from 'react-router-dom';


interface Props {}

function Login(props:Props) {
    var dispatch = useDispatch()
    var navigate = useNavigate();
 
    const onFinish = async (values: any) => {
        console.log('Success:', values);
        var res = await service.admin.adminLogin( values )
        notification.destroy();
            notification.destroy();
        if( res.data.code == 200 ){
            notification.success({message:'登陆成功!'});
            dispatch({ type:'SAVE_USERINFO',payload: res.data.data })
            navigate('/index');
        }else{
            notification.error({message:'登陆失败!'});
        }
    };

    //用户名的验证器
    var adminNamne = (rule:any, value:any, callback:any) => {
        if( value.length<=6 || value == 'admin' ){
            callback();
        }else{
            callback(new Error('请输入正确的用户名!'));
        }
    }
    //密码的验证器
    var password = (rule:any, value:any, callback:any) => {
        if( /^\d{6}$/.test( value ) ){
            
            callback();
        }else{
            callback(new Error('请输入正确的密码!'));
        }
    }

    return (
        <div className='login'>
            <h1 className="title">后台管理系统</h1>
            <Form
                className='form'
                style={{ minWidth: 300 }}
                onFinish={onFinish}
                autoComplete="off"
            >
                <Form.Item
                name="adminname"
                rules={[{ validator: adminNamne }]}
                >
                    <Input/>
                </Form.Item>

                <Form.Item
                name="password"
                rules={[{ validator: password }]}
                >
                    <Input.Password />
                </Form.Item>

                <Form.Item>
                    <Button block type="primary" htmlType="submit">
                        登陆
                    </Button>
                </Form.Item>
            </Form>
        </div>
    );
}

export default Login;